<template>
  <div class="Roles-container">
    <!-- 导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->

    <el-card>
      <el-row>
        <el-button type="primary">添加角色</el-button>
      </el-row>

      <el-table :data="rolelist" border style="100%" highlight-current-row>
        <!-- 折叠区域 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row v-for="(item, index) in scope.row.children" :key="item.id" class="vcenter">
              <!-- 渲染一级菜单 -->
              <el-col :span="5" class="bom_border" :class="[index === 0  ? 'top_border' : '', 'vcenter']">
                <el-tag closable @close="removeRightByid(scope.row, item.id)"> {{item.authName}}</el-tag>
              </el-col>

              <!-- 渲染二三级菜单 -->
              <el-col :span="19">
                <!-- 循环二级权限 -->
                <el-row v-for="(item2, index2) in item.children" :key="item2.id">
                  <el-col :span="6" :class="[index2 === 0  ?  'top_border' :'' , 'vcenter']">
                    <el-tag type="success" closable @close="removeRightByid(scope.row, item2.id)"> {{item2.authName}}
                    </el-tag>
                  </el-col>
                  <!-- 三级标签 -->
                  <el-col :span="18" :class="[index2 === 0  ? 'top_border' : '']">
                    <el-tag type="warning" v-for="(item3) in item2.children" :key="item3.id" closable
                      @close="removeRightByid(scope.row, item3.id)">{{item3.authName}}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <!-- {{scope.row}} -->
          </template>
        </el-table-column>
        <!-- 索引区域 -->
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" icon="el-icon-setting">编辑</el-button>
            <el-button type="danger" size="mini" icon="el-icon-delete">删除</el-button>
            <el-button type="warning" size="mini" icon="el-icon-s-custom" @click="ShowJurisdiction(scope.row)">分配权限
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 弹出分配权限框 -->
      <el-dialog title="分配权限" :visible.sync="ShowdialogVisible" width="30%" @close="setRightDialogClosed">

        <!-- 树形组件 -->
        <el-tree :data="rightslist" show-checkbox node-key="id" :default-checked-keys="DefaultChecked"
          :props="defaultProps" default-expand-all ref="treeRef">
        </el-tree>


        <span slot="footer">
          <el-button @click="ShowdialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="allotRights">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>

  </div>
</template>


<script>
  export default {
    data() {
      return {
        rolelist: [],
        ShowdialogVisible: false,
        rightslist: [],
        // 树形控件的属性绑定
        defaultProps: {
          children: 'children',
          label: 'authName'
        },
        //  默认的选中的节点id
        DefaultChecked: [],

        roleId:[]
      }
    },

    created() {
      this.getRolelist()
    },

    methods: {
      async getRolelist() {
        const {
          data: res
        } = await this.$http.get('roles')

        if (res.meta.status !== 200) {
          return this.$message.error('获取角色列表失败')
        } else {
          this.$message.success('获取角色列表成功')
        }

        this.rolelist = res.data
        console.log(this.rolelist);
      },


      async removeRightByid(role, rightId) {
        const confirmResule = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => err)

        if (confirmResule !== 'confirm') {
          return this.$message.info('取消删除成功')
        }

        const {
          data: res
        } = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)

        if (res.meta.status !== 200) {
          return this.$message.error('删除权限失败')
        }
        this.$message.success('删除权限成功')

        //  this.getRolelist()
        role.children = res.data
      },

      // 获取到的权限列表的数据
      async ShowJurisdiction(role) {
        this.roleId = role.id
        const {
          data: res
        } = await this.$http.get('rights/tree')
        this.rightslist = res.data
        console.log(res.data);
        //  获取递归三级节点的id
        this.getleafkeys(role, this.DefaultChecked)
        this.ShowdialogVisible = true
      },

      // 递归获取三级权限的id
      // 定义函数节点值和舒数组 如果节点有children 就把id放在DefaultChecked数组中
      getleafkeys(node, arr) {
        if (!node.children) {
          return arr.push(node.id)
        }
        // 如果节点下面有children就继续往下查找
        // 不明白
        node.children.forEach(item => this.getleafkeys(item, arr))
      },
      // 监听分配权限对话框的关闭事件
      setRightDialogClosed() {
        this.DefaultChecked = []
      },
     async allotRights(){
        const keys = [
          ...this.$refs.treeRef.getCheckedKeys(),
          ...this.$refs.treeRef.getHalfCheckedKeys(),
        ]
             const idstr = keys.join(',')

          const{data:res} = await this.$http.post(`roles/${this.roleId}/rights`,{rids: idstr})

          if(res.meta.status !== 200){
            return this.$message.error('分配权限失败')
          }
          this.$message.success('分配权限成功')

          this.getRolelist()

          this.ShowdialogVisible = false
      }
    }
  }
</script>


<style lang="less" scoped>
  .el-tag {
    margin: 5px;
  }

  .bom_border {
    border-bottom: 1px solid gray;
  }

  .top_border {
    border-top: 1px solid gray;
  }

  .vcenter {
    display: flex;
    align-items: center;
  }
</style>